package servlet.shopping;

import com.alibaba.fastjson.JSONObject;
import service.SearchIndexpagere;
import service.ShoppingService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/deleteshoping")
public class DeleteShopping extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String idsString = req.getParameter("ids");
        // 创建一个集合用于存放每个 id 值
        List<String> idsList = new ArrayList<>();
        JSONObject jsonResponse = new JSONObject();
        //设置响应对象类型
        resp.setContentType("application/json;charset=utf-8");
        // 判断 idsString 是否为空
        if (idsString != null && !idsString.isEmpty()) {
            // 使用逗号分隔符将字符串拆分成 id 值数组
            String[] idsArray = idsString.split(",");
            // 将每个 id 值存入集合中
            for (String id : idsArray) {
                idsList.add(id);
            }
            int i = 0;
            ShoppingService shoppingService = new ShoppingService();
            for (String s : idsList) {
                 i = shoppingService.deleteShopping(s);
            }
            if (i ==1){
                // 设置响应的 JSON 数据
                jsonResponse.put("code", 1);
                // 将 JSON 对象转换为字符串
                String jsonString = jsonResponse.toJSONString();
                // 返回 JSON 字符串给客户端
                PrintWriter out = resp.getWriter();
                out.print(jsonString);
                out.flush();
            }
//            shoppingService.deleteShopping()
        }else {
            System.out.println("购物车为空 无法删除");
            jsonResponse.put("code", 0);
            // 将 JSON 对象转换为字符串
            String jsonString = jsonResponse.toJSONString();
            // 返回 JSON 字符串给客户端
            PrintWriter out = resp.getWriter();
            out.print(jsonString);
            out.flush();
        }
//
//        // 创建 JSON 对象
//        if (i==1){
//            // 设置响应的 JSON 数据
//            jsonResponse.put("code", 1);
//            // 将 JSON 对象转换为字符串
//            String jsonString = jsonResponse.toJSONString();
//            // 返回 JSON 字符串给客户端
//            PrintWriter out = resp.getWriter();
//            out.print(jsonString);
//            out.flush();
//        }else{
//            jsonResponse.put("code", 0);
//            // 将 JSON 对象转换为字符串
//            String jsonString = jsonResponse.toJSONString();
//            // 返回 JSON 字符串给客户端
//            PrintWriter out = resp.getWriter();
//            out.print(jsonString);
//            out.flush();
//        }


    }
}
